import cv2
import siot
from time import sleep

#配置服务器地址
SERVER = "192.168.31.233"
CLIENT_ID = ""

IOT_pubTopic  = 'deng/face' #主题 用户名 密码
IOT_UserName ='siot'
IOT_PassWord ='dfrobot'

siot.init(CLIENT_ID, SERVER, user=IOT_UserName, password=IOT_PassWord)
siot.connect()
siot.loop()


#向SIoT发送信息
def guandeng():
    mess="0"
    siot.publish(IOT_pubTopic, mess)

def kaideng():
    mess="1"
    siot.publish(IOT_pubTopic, mess)
    
def lower():
    mess="lower"
    siot.publish(IOT_pubTopic, mess)
    
def brighter():
    mess="brighter"
    siot.publish(IOT_pubTopic, mess)
    
#载入提前下载好的模型
face_cascade = cv2.CascadeClassifier('/home/cfz/桌面/inno maker/moxing/face.xml')
smile_cascade = cv2.CascadeClassifier('/home/cfz/opencv-4.6.0/data/haarcascades/haarcascade_smile.xml')


# 调用摄像头摄像头
camera = cv2.VideoCapture(0)
sleep(1)
smiles=[]
maintain_f=maintain_e=0
while True:
    # 获取摄像头拍摄到的画面
    f=0;e=0
    ret,img = camera.read()
    if ret:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
    #人脸检测
    for (x,y,w,h) in faces:
    	# 画出人脸框，颜色，画笔宽度
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,225,0),2)
    	# 框选出人脸区域，在人脸区域而不是全图中进行人眼检测，节省计算资源
        face_area = img[y:y+h, x:x+w]
        
        # 笑脸检测
        # 用笑脸级联分类器引擎在人脸区域进行笑脸识别，返回的smiles为笑脸坐标列表
        smiles = smile_cascade.detectMultiScale(
                        face_area,
                        scaleFactor=1.1,
                        minNeighbors=25,
                        minSize=(40, 40),
                        flags=cv2.CASCADE_SCALE_IMAGE
        )
        for (ex,ey,ew,eh) in smiles:
            # 画出笑脸框，绿色，画笔宽度
            img = cv2.rectangle(img,(ex+x,ey+y),(ex+ew+x,ey+eh+y),(255,0,0),2)
    
    # 人脸以及笑脸的个数
    f= len(faces)
    e= len(smiles)
    
    #人脸及笑脸存在一段时间后作出动作
    if f==0:maintain_f-=1
    else:maintain_f+=1
        
    if e==0:maintain_e-=1
    else:maintain_e+=1
        
    if maintain_f==60:
        kaideng();maintain_f=0
    elif maintain_f==-60:
        guandeng();maintain_f=0
        
    if maintain_e==30:
        brighter();maintain_e=0
    elif maintain_e==-30:
        lower();maintain_e=0
        
	# 实时展示效果画面
    cv2.imwrite('test.jpg', img)
    cv2.imshow('show',img)
    
    # 每33毫秒监听一次键盘动作
    key=cv2.waitKey(33) 
    if key == 27:  #键盘按esc退出
        break

# 关闭所有窗口
camera.release()
cv2.destroyAllWindows()